package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Transactional
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findAll() {
        List<Category> categoryList = categoryMapper.findAll();
        return categoryList;
    }

    @Override
    public void save(Category category) {
        category.setId(IdUtil.getSnowflake(1, 1).nextId());
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        category.setCreateUser(1L);
        category.setUpdateUser(1L);
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
        //1.补齐参数
       /* //todo 临时写死
        category.setUpdateUser(1L);
        category.setUpdateTime(new Date());*/

        //2. 调用mapper更新
        categoryMapper.updateById(category);
    }

    @Override
    public ResultInfo delete(Long id) {
        Integer number1 = categoryMapper.findDishById(id);
        Integer number2 = categoryMapper.findSetMealById(id);
        //查找菜品或套餐的数量
        if (number1 > 1) {
            return ResultInfo.error("菜品名下有菜,不能删除!");
        }
        if (number2 > 2) {
            return ResultInfo.error("套餐名下有菜,不能删除!");
        }
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }
    @Override
    public List<Category> findByType(Integer type) {
        //select * from category where type = #{}
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,type);

        return categoryMapper.selectList(wrapper);
    }

}
